﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ThreeByte.TaskModel;
using System.ComponentModel;
using ThreeByte.ActiveDeck.Config;
using ThreeByte.ActiveDeck.Service;
using System.Windows.Controls;
using ThreeByte.ActiveDeck.Content;
using System.Windows.Threading;
using System.Xml.Linq;
using ThreeByte.ActiveDeck.Data;
using System.Diagnostics;
using System.IO;
using log4net;

namespace ThreeByte.ActiveDeck.AddIn.Config
{
    public class RetrieveResourcesTask : AsyncTaskBase
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(RetrieveResourcesTask));

        private string PresentationID;
        private WebServiceClient Client;
        public HashSet<Guid> AllResources { get; private set; }
        private static readonly int TAKE_COUNT = 5000;


        public RetrieveResourcesTask(string presentation, WebServiceClient client) {
            PresentationID = presentation;
            Client = client;
            Name = string.Format("Retrieving Cached Resources...");
            AllResources = new HashSet<Guid>();
        }

        protected override void Run(BackgroundWorker bw, DoWorkEventArgs e) {

            int progress = 0; //Fake this number
            bool hasMoreResources = true;
            while(hasMoreResources) {
                if(bw.CancellationPending) {
                    e.Cancel = true;
                    return;
                }
                Status = string.Format("Retrieved {0}", AllResources.Count);
                bw.ReportProgress(progress % 100);
                progress += 10;

                List<Guid> ids = Client.GetResourceList(PresentationID, TAKE_COUNT, AllResources.Count);
                hasMoreResources = (ids.Count == TAKE_COUNT);
                foreach(Guid g in ids) {
                    AllResources.Add(g);
                }
            }

            bw.ReportProgress(100);
            Status = "All resources retrieved";   
        }

    }
}
